var laypage = layui.laypage;
var layer = layui.layer;
var form = layui.form;

// ?? 定义请求参数对象
let query = {
  advimgdesc: '',  //广告图描述
  advimgpos: '', // 广告位名称
  page: 1, // 第几页数据
  limit: 10 // 每页的数量
}
// !获取广告位的数据
getAdCate()
async function getAdCate() {
  const { data } = await axios.get('/ydd_advpos/all')
  const optionStr = data.data.map(item => `<option value="${item.id}">${item.advposname}</option>`).join('')
  $('select[name=city]').html('<option value="">请选择广告位</option>' + optionStr)
  form.render();
}


// todo 1、获取广告图列表的信息
getAdImgList()
async function getAdImgList() {
  try {
    const { data: { data } } = await axios.get('/ydd_advimg/list', { params: query })
    // console.log(data);
    let str = data.data.map(item => `<tr>
      <td><input type="checkbox"></td>
      <td>${item.id}</td>
      <td>${item.advposname}</td>  
      <td>${item.advimgdesc}</td>
      <td><img src="http://124.223.14.236:8060/${item.advimgsrc}" alt=""></td>
      <td>${item.advimglink}</td>
      <td>
        <div class="lxj_oper_circle">
          <i class="layui-icon layui-icon-edit lxj_edit" data-id=${item.id}  data-fixed=${item.advimgpos}></i>
        </div>
        <div class="lxj_oper_circle">
          <i class="layui-icon layui-icon-delete lxj_delete" data-id=${item.id}></i>
        </div>
      </td>
    </tr>`).join('')
    $('tbody').html(str)
    renderAdImgPage(data.count)
  } catch (error) {
    console.log(error.response);
  }
}
// todo 2、渲染表格的分页
function renderAdImgPage(count) {
  laypage.render({
    elem: 'lxj_renderpage',
    count: count, //数据总数，从服务端得到
    limits: [1, 2, 5, 8, 10],
    limit: query.limit,  // 当前每页条数
    curr: query.page,   // 当前第几页
    layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
    jump(obj, first) {
      //obj包含了当前分页的所有参数，比如：
      // console.log(obj.curr);  //得到当前页，以便向服务端请求对应页的数据。
      // console.log(obj.limit); //得到每页显示的条数
      query.page = obj.curr
      query.limit = obj.limit
      //首次不执行
      if (!first) {
        getAdImgList()
      }
    }
  });
}

// todo 3-1 关闭或显示搜索区
let openorclose = true
$('.lxj_circle:nth-child(1)').on('click', function () {
  // console.log(1);
  if (openorclose) {
    $('#lxj_serach').hide()
    openorclose = false
  } else {
    $('#lxj_serach').show()
    openorclose = true
  }
})
// todo 3-2 刷新功能
$('.lxj_circle:nth-child(2)').on('click', function () {
  getAdImgList()
})

// todo  4 点击新增广告图 显示弹窗
var addadvindex
const advimgStr = `<form  id="lxj_addForm" class="layui-form">
<!-- 第一行 -->
<div class="layui-form-item">
  <label class="layui-form-label">广告位</label>
  <div class="layui-input-block">
    <select name="advimgpos" lay-verify="required" id="dyncity">
      <option value="">请选择广告位</option>
    </select>
  </div>
</div>
<!-- 第二行   -->
<div class="layui-form-item">
  <label class="layui-form-label">广告图描述</label>
  <div class="layui-input-block">
    <textarea name="advimgdesc" placeholder="请输入广告位描述"  class="layui-textarea" style="width: 250px"></textarea>
  </div>
</div>
<!-- 第三行   -->
<div class="layui-form-item">
  <label class="layui-form-label">广告图链接</label>
  <div class="layui-input-block">
    <input type="text" name="advimglink" required lay-verify="required" placeholder="请输入广告图链接" autocomplete="off"
      class="layui-input"  style="width: 250px">
  </div>
</div>
<!-- 第四行 -->
<div class="layui-form-item">
  <label class="layui-form-label">广告图</label>
  <div class="layui-input-block">
    <button type="button" class="layui-btn layui-btn-normal" id="upchuan">点击上传</button>
    <input type="file" style="display: none;" id="file" accept="image/jpeg,image/png,image/gif,image/bmp">
    <div  id="showimg">
      <img src=""  id="img" width="100%"/>
    </div>
  </div>
</div>

<div class="layui-form-item">
  <div class="layui-input-block">
    <button class="layui-btn layui-btn-warm" lay-submit lay-filter="formDemo">添加</button>
  </div>
</div>
</form>`


let path, file
$('.lxj_btn1').on('click', function () {
  file = undefined
  path = undefined
  addadvindex = layer.open({
    type: 1,
    title: ['添加广告图', 'font-size:18px;color:blue'],
    content: advimgStr,
    area: ['683px', '520px'],
    success: async function (layero) {
      const { data } = await axios.get('/ydd_advpos/all')
      const optionStr = data.data.map(item => `<option value="${item.id}">${item.advposname}</option>`).join('')
      $('#dyncity').html('<option value="">请选择广告位</option>' + optionStr)
      // console.log($('#dyncity'));
      form.render();
    }
  })
  // console.log(path);
  // 点击显示文件域
  $('#upchuan').on('click', function () {
    $('#file').click()
  })
  // 监听文件的上传 
  $('#file').on('change', async function () {
    file = this.files[0] // 用户选择的文件
    if (!file) {
      return layer.msg('请选择图片!')
    }
    const fd = new FormData()
    fd.append('file', file)
    // 上传图片 显示图片 
    let { data } = await axios.post('/common/upload', fd, { params: { "type": "images" } })
    $('#img').attr('src', '') // 先清空上一次的图片
    $('#upchuan').hide()
    $('#showimg').show()
    $('#img').attr('src', "http://124.223.14.236:8060/" + data.data.savePath)
    path = data.data.savePath

  })
  // 关闭图片 显示 上传按钮
  $('#showimg').on('click', function () {
    $('#showimg').hide()
    $('#upchuan').show()
    file = undefined
    path = undefined
  })
})

// todo 4-1 监听表单 拿数据 发请求 新增广告图
$('body').on('submit', '#lxj_addForm', async function (e) {
  e.preventDefault()
  const basedata = $(this).serialize()
  const finaldata = basedata + '&advimgsrc=' + path
  console.log(finaldata);
  console.log(file);
  if (!file) {
    // 说明没选择图片
    return layer.msg('请选择图片！')
  }
  const { data } = await axios.post('/ydd_advimg/add', finaldata)
  if (data.errno !== 0) {
    return layer.msg('添加广告图失败！')
  }
  layer.msg('添加广告图成功！')
  layer.close(addadvindex)
  getAdImgList()
})


// todo 5 修改广告图 功能
let adeditindex
const adeditStr = `<form id="lxj_editForm" class="layui-form" lay-filter="FormEDG">
<!-- id -->
<div class="layui-form-item layui-hide">
  <label class="layui-form-label ">ID</label>
  <div class="layui-input-block">
    <input type="text" name="id" readonly  autocomplete="off" class="layui-input"  style="width: 250px">
  </div>
</div>
<!-- 第一行 -->
<div class="layui-form-item">
  <label class="layui-form-label">广告位</label>
  <div class="layui-input-block">
    <select name="advimgpos" lay-verify="required" id="dyncity">
      <option value="">请选择广告位</option>
    </select>
  </div>
</div>
<!-- 第二行   -->
<div class="layui-form-item">
  <label class="layui-form-label">广告图描述</label>
  <div class="layui-input-block">
    <textarea name="advimgdesc" placeholder="请输入广告位描述"  class="layui-textarea" style="width: 250px"></textarea>
  </div>
</div>
<!-- 第三行   -->
<div class="layui-form-item">
  <label class="layui-form-label">广告图链接</label>
  <div class="layui-input-block">
    <input type="text" name="advimglink" required lay-verify="required" placeholder="请输入广告图链接" autocomplete="off"
      class="layui-input"  style="width: 250px">
  </div>
</div>
<!-- 第四行 -->
<div class="layui-form-item">
  <label class="layui-form-label">广告图</label>
  <div class="layui-input-block">
    <button type="button" class="layui-btn layui-btn-normal" id="upchuan" style="display:none">点击上传</button>
    <input type="file" style="display: none;" id="file" accept="image/jpeg,image/png,image/gif,image/bmp">
    <div  id="showimg">
      <img src=""  width="100%"/>
    </div>
  </div>
</div>

<div class="layui-form-item">
  <div class="layui-input-block">
    <button class="layui-btn" lay-submit lay-filter="formDemo">修改</button>
  </div>
</div>
</form>`

// todo 5-1 点击编辑按钮 弹出当前id对应的修改广告图弹窗
let file1
$('.lxj_table').on('click', '.lxj_edit', async function () {
  const id = $(this).attr('data-id')
  const fixedID = $(this).attr('data-fixed')
  const { data: { data } } = await axios.get('/ydd_advimg/rowInfo', { params: { id } })   // 根据id 获取详情信息
  file1 = data.advimgsrc // 解决？ 修改信息时，只修改文字，不会触发图片的change事件，那么file1为undefiend 则触发请选择图片！！
  adeditindex = layer.open({
    type: 1,
    title: ['修改广告图', 'font-size:18px;color:orange'],
    content: adeditStr,
    area: ['683px', '520px'],
    success: async function (layero) {
      const { data } = await axios.get('/ydd_advpos/all')
      const optionStr = data.data.map(item => `<option value="${item.id}">${item.advposname}</option>`).join('')
      $('#dyncity').html('<option value="">请选择广告位</option>' + optionStr)
      form.render();
      $('#dyncity').val(fixedID)
      form.render();
    }
  })
  form.val("FormEDG", data)

  // todo 5-2 处理 图像
  $('#showimg').show()
  $('#showimg img').attr('src', "http://124.223.14.236:8060/" + data.advimgsrc)

  //关闭图片 显示 上传按钮
  $('#showimg').on('click', function () {
    $('#showimg').hide()
    $('#upchuan').show()
    file1 = undefined
  })
  // 点击显示文件域
  $('#upchuan').on('click', function () {
    $('#file').click()
  })

  // 监听文件的上传 
  $('#file').on('change', async function () {
    file1 = this.files[0] // 用户选择的文件
    if (!file1) {
      return layer.msg('请选择图片!')
    }
    const fd = new FormData()
    fd.append('file', file1)

    // fd.forEach(item => {
    //   console.log(item);
    // })
    // 上传图片 显示图片 
    let { data } = await axios.post('/common/upload', fd, { params: { "type": "images" } }, { headers: { 'Content-Type': 'multipart/form-data' } })
    console.log(data);
    $('#showimg img').attr('src', '') // 先清空上一次的图片
    $('#upchuan').hide()
    $('#showimg').show()
    $('#showimg img').attr('src', "http://124.223.14.236:8060/" + data.data.savePath)
    path1 = data.data.savePath
    console.log(path1);
  })

  path1 = data.advimgsrc
  // console.log(path1);
})

//  todo 5-2 发请求更新广告图的信息
$('body').on('submit', '#lxj_editForm', async function (e) {
  e.preventDefault()
  const basedata = $(this).serialize()
  const finaldata = basedata + '&advimgsrc=' + path1
  console.log(finaldata);
  if (!file1) {
    // 说明没选择图片
    return layer.msg('请选择图片！!')
  }
  const { data } = await axios.post('/ydd_advimg/update', finaldata)
  if (data.errno !== 0) {
    return layer.msg('修改广告图信息失败！')
  }
  layer.msg('修改广告图信息成功！')
  layer.close(adeditindex)
  getAdImgList()
})


// todo 6 删除广告图的信息
$('.lxj_table').on('click', '.lxj_delete', function () {
  const did = $(this).attr('data-id')
  layer.confirm('确认删除吗？', { icon: 3, title: '提示' }, async function (index) {
    const { data } = await axios.get('/ydd_advimg/del', { params: { id: did } })
    if (data.errno !== 0) {
      // 删除失败
      return layer.msg(data.errmsg)
    }
    // 删除成功
    layer.msg('删除成功！')
    layer.close(index);
    getAdImgList()
  });
})


//todo 7 搜索与重置功能
const serach_val = $('input[name=advpos_title]')
const cityname = $('select[name=city]')
$('#search').on('click', function () {
  query.advimgdesc = serach_val.val()
  query.advimgpos = cityname.val()
  getAdImgList()
})
$('#reset').on('click', function () {
  serach_val.val('')
  query.advimgdesc = ''
  query.advimgpos = ''
  $('select[name=city]').val('')
  getAdImgList()
})
